﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using Red.Core.GoogleAnalytics;

namespace Red.Launcher
{
    public partial class SettingsView
    {
        private Dictionary<string, string> Changes { get; set; }
        private bool AnalyticsInitialised { get; set; }

        partial void InitializeAnalytics()
        {
            if ( AnalyticsInitialised )
                return;

            Changes = new Dictionary<string, string>();

            ThemeChanged += ( string theme ) => { Changes[ "theme" ] = theme; };
            AccentChanged += ( string accent ) => { Changes[ "accent" ] = accent; };

            PropertyChanged += ( object sender, PropertyChangedEventArgs e ) =>
            {
                if ( e.PropertyName == "ToolkitPackagesInstallationDirectory" )
                {
                    Changes[ e.PropertyName ] = ToolkitPackagesInstallationDirectory;
                }
                else if ( e.PropertyName == "EnginePackagesInstallationDirectory" )
                {
                    Changes[ e.PropertyName ] = EnginePackagesInstallationDirectory;
                }
            };

            Settings.StaticPropertyChanged += ( object sender, PropertyChangedEventArgs e ) =>
            {
                PropertyInfo property = typeof( Settings ).GetProperty( e.PropertyName );

                object value = property.GetValue( null, null );

                if ( value != null )
                {
                    string valueStr = value.ToString();

                    if ( !String.IsNullOrWhiteSpace( valueStr ) && valueStr != "uninitialised" )
                    {
                        Changes[ e.PropertyName ] = valueStr;
                    }
                }
            };

            AnalyticsInitialised = true;
        }

        public void SendAnalytics()
        {
            foreach ( KeyValuePair<string, string> change in Changes )
            {
                GoogleAnalyticsService.Instance.SendEvent( change.Key, "Setting Changed", change.Value );
            }
        }
    }
}
